<template>
  <div class='container'>
    <el-card>
      <div class="form-box">
        <div class="search-box">
          <div>
          <span class="label">关键字</span>
          <el-input v-model="baseForm.keyword" placeholder="根据文章标题搜索" size="small"></el-input>
        </div>
        <div>
          <span class="label">状态</span>
          <el-select v-model="baseForm.state" size="small" placeholder="请选择">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="button-box">
          <el-button size="small" @click="emptyBaseForm">清除</el-button>
          <el-button size="small" type="primary" @click="searchData">搜索</el-button>
        </div>
        </div>
        <el-button size="small" type="success" icon="el-icon-edit" @click="handleAddData">新增技巧</el-button>
      </div>
      <el-alert
        :title="'数据总共'+counts+'条'"
        type="info"
        show-icon
        style="margin: 20px 0">
      </el-alert>
      <!-- 表格 -->
         <el-table
            :data="tableData"
            style="width: 100%;">
            <el-table-column
              type="index"
              label="序号"
              width="80">
            </el-table-column>
            <el-table-column
              prop="title"
              label="文章标题"
              width="400"
              >
              <template v-slot="{ row }">
                {{ row.title }}
              <a :class="{ 'el-icon-film': row.videoURL ? true : false }" href="javascript:;" @click.prevent="handleClickVideo(row.videoURL)"></a>
              </template>
            </el-table-column>
            <el-table-column
              prop="visits"
              label="阅读数">
            </el-table-column>
            <el-table-column
              prop="username"
              label="录入人">
            </el-table-column>
             <el-table-column
              prop="createTime"
              label="录入时间">
              <template v-slot="{ row }">
              {{ row.createTime | formatDate}}
              </template>
            </el-table-column>
             <el-table-column
              prop="state"
              label="状态"
              width="100"
              :formatter="formatterStatus"
              >

            </el-table-column>
             <el-table-column
              label="操作"
              width="180">
              <template v-slot="{ row }">
                <el-button @click="handleClickPreview(row)" type="text" size="small">预览</el-button>
                <el-button @click="handleClickEnable(row)" type="text" size="small" >{{row.state === 0 ? '启用' :'禁用'}}</el-button>
                <!-- <el-button @click="handleClick(row)" type="text" size="small" v-else>禁用</el-button> -->
                <el-button @click="handleClickEdit(row)" type="text" size="small"
                :disabled="row.state === 0">修改</el-button>
                <el-button @click="handleClickDelete(row)" type="text" size="small"
                :disabled="row.state === 0">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="counts"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pagesize"
            background
            layout=" prev, pager, next,sizes, jumper">
          </el-pagination>
    </el-card>
    <!-- 预览弹层 -->
    <el-dialog title="预览文章" :visible='previewDialog' width="800px" @close="previewDialogClose">
      <div>
        <h1>{{ clickRow.title }}</h1>
        <span>{{ clickRow.createTime | formatDate }}</span> <span style="padding: 0 10px">{{ clickRow.username }}</span><i class="el-icon-view">  {{ clickRow.visits }}</i>
      </div>
      <div v-html="clickRow.articleBody" style="background: #f5f5f5;
    padding: 10px;"></div>
    </el-dialog>
    <!-- 视频弹层 -->
    <div class="video-preview" v-if="dialogVideoVisble" >
      <div class="close" @click="videoDialogClose">
        <span class="el-icon-close"></span>
      </div>
      <div class="box">
        <video :src="videoURL" autoplay></video>
      </div>
    </div>
    <!-- 修改 / 添加 弹层 -->
    <el-dialog :title=" clickRow.id ? '修改文章' : '添加文章'" :visible="editDialog" width="800px" @close="btnCancel">
      <el-form ref="rditForm" label-width="100px" style="padding-right: 20px" :model="clickRow" :rules="rules">
        <el-form-item label="文章标题:" prop="title">
          <el-input v-model="clickRow.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" prop="articleBody">
          <editor :textContent="clickRow.articleBody" v-model="clickRow.articleBody" @change="getEditorContent"></editor>
        </el-form-item>
        <el-form-item label="视频地址:">
          <el-input v-model="clickRow.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end" slot="footer">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button size="small" type="primary" @click="btnOK">确认</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { status } from '@/api/hmmm/constants'
import { list, changeState, update, add, remove } from '@/api/hmmm/articles'
import Editor from '../components/editor'
export default {
  components: {
    Editor
  },
  data () {
    return {
      baseForm: {
        keyword: null,
        state: null
      },
      // {value: 1,label: '启用'},{value: 0,label: '禁用'}
      stateList: status, // 启用、禁用常量
      tableData: [], // 表格数据
      currentPage: 1, // 当前选中的页码
      counts: 0, // 总数
      pagesize: 10, // 每页条数
      previewDialog: false, // 预览弹层
      clickRow: {}, // 当前点击的那一列
      videoURL: '', // 点击的视频
      dialogVideoVisble: false, // 视频弹层显示
      editDialog: false, // 修改弹层显示
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.getArticlesList()
  },
  methods: {
    // 每页多少
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getArticlesList()
    },
    // 当前页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getArticlesList()
    },
    // 搜索
    searchData () {
      this.getArticlesList()
    },
    // 列表
    async getArticlesList () {
      const { data } = await list({
        page: this.currentPage,
        pagesize: this.pagesize,
        ...this.baseForm
      })
      console.log(data)
      this.tableData = data.items // 存储接口返回的数据
      this.counts = data.counts // 保存总数
    },
    // 格式化状态
    formatterStatus (row, column, cellValue, index) {
      const obj = status.find(item => item.value === cellValue)
      return obj ? obj.label : '未知'
    },
    // 点击预览弹层打开
    handleClickPreview (row) {
      // 弹出弹层
      this.previewDialog = true
      this.clickRow = row
    },
    // 点击预览弹层关闭
    previewDialogClose (row) {
      // 关闭弹层
      this.previewDialog = false
      this.clickRow = {}
    },
    // 视频播放
    handleClickVideo (url) {
      this.dialogVideoVisble = true // 显示弹层
      this.videoURL = url // 视频链接
    },
    // 视频关闭
    videoDialogClose () {
      this.dialogVideoVisble = false
      this.videoURL = ''
    },
    // 点击启用，修改后台数据
    async handleClickEnable (row) {
      try {
        const result = await changeState({
          id: row.id,
          state: row.state === 0 ? 1 : 0
        })
        console.log(result)
        this.$message.success('修改状态成功')
        this.getArticlesList()
      } catch (error) {
        console.log(error)
      }
    },
    // 清空表单
    emptyBaseForm () {
      this.baseForm = {
        keyword: null,
        state: null
      }
      this.getArticlesList()
    },
    // 修改文章
    handleClickEdit (row) {
      // 显示弹层
      this.editDialog = true
      this.clickRow = row
    },
    async btnOK () {
      // 表单校验通过后
      await this.$refs.rditForm.validate()
      // 有id，就是修改
      if (this.clickRow.id) {
        try {
          await update(this.clickRow)
          this.$message.success('修改数据成功')
        } catch (error) {
          this.$message.error(error)
        }
      } else {
        // 无id 就是添加
        try {
          await add(this.clickRow)
          this.$message.success('操作成功')
        } catch (error) {
          this.$message.error(error)
        }
      }
      this.editDialog = false
      // 最后重置表单校验
      await this.$refs.rditForm.resetFields()
      this.clickRow = {}
    },
    btnCancel () {
      this.editDialog = false
      this.clickRow = {}
    },
    handleClickDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getArticlesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleAddData () {
      this.editDialog = true
    },
    getEditorContent (val) {
      this.clickRow.articleBody = val
    }
  }
}
</script>

<style rel="stylesheet/scss" scoped lang="scss">
.container {
  padding: 10px;
  .form-box {
    display: flex;
    justify-content: space-between;
    .search-box {
      padding-left: 20px;
      display: flex;
      color: #606266;
      >div {
        display: flex;
        align-items: center;
      }
      .label {
        width: 85px;
        font-size: 14px;
        font-weight: bold;
        text-align: right;
        padding-right: 20px;
      }
    }
    .button-box {
        padding-left: 15px;
    }
  }
  .el-pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .el-icon-film {
    color: blue;
    font-size: 20px;
  }
  .video-preview {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,.3);
    z-index: 9999;
    .close {
      position: absolute;
      top: 30px;
      left: 50%;
      right: 50%;
      width: 50px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background: rgba(0,0,0,.4);
      border-radius: 50%;
      .el-icon-close {
        width: 20px;
        height: 20px;
        color: #fff;
        font-size: 20px;
      }
    }
    .box {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 800px;
      height: 600px;
      video {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
